package com.hm.cms.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.querydsl.QPageRequest;
import org.springframework.stereotype.Service;

import com.hm.cms.mongo.domain.CmsContactWay;
import com.hm.cms.mongo.domain.QCmsContactWay;
import com.hm.cms.mongo.vo.CmsContactWayVo;
import com.hm.cms.share.repository.mongo.CmsContactWayRepository;
import com.hm.cms.share.service.CmsContactWayService;
import com.hm.common.common.BeanUtil;
import com.hm.common.exception.ErrorCode;
import com.hm.common.exception.ServiceException;
import com.hm.common.model.PageInfo;

/**
 * @author shishun.wang
 * @date 下午2:14:36 2016年8月6日
 * @version 1.0
 * @describe
 */
@Service
public class CmsContactWayServiceImpl implements CmsContactWayService {

	@Autowired
	private CmsContactWayRepository cmsContactWayRepository;

	@Override
	public CmsContactWayVo getCmsContactWay(String id) {
		CmsContactWay contactWay = cmsContactWayRepository.findOne(id);
		if (null == contactWay) {
			throw ServiceException.warning(ErrorCode.DATA_NOT_FOUND);
		}

		return (CmsContactWayVo) BeanUtil.copyProperties(new CmsContactWayVo(), contactWay);
	}

	@Override
	public String addCmsContactWay(CmsContactWayVo contactWayVo, String operationUser) {
		CmsContactWay contactWay = new CmsContactWay();
		{
			contactWay = (CmsContactWay) BeanUtil.copyProperties(contactWay, contactWayVo);
			contactWay.setCreateUser(operationUser);
		}

		return cmsContactWayRepository.save(contactWay).getId();
	}

	@Override
	public String updateCmsContactWay(CmsContactWayVo contactWayVo, String operationUser) {
		CmsContactWay contactWay = cmsContactWayRepository.findOne(contactWayVo.getId());
		if (null == contactWay) {
			throw ServiceException.warning(ErrorCode.DATA_NOT_FOUND);
		}
		contactWay = (CmsContactWay) BeanUtil.copyProperties(contactWay, contactWayVo);

		return cmsContactWayRepository.save(contactWay).getId();
	}

	@Override
	public String deleteCmsContactWay(CmsContactWayVo contactWayVo, String operationUser) {
		cmsContactWayRepository.delete(contactWayVo.getId());
		return contactWayVo.getId();
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public PageInfo<CmsContactWayVo> queryCmsContactWay(Integer pageNumber, Integer pageSize) {
		PageInfo<CmsContactWayVo> pageInfo = new PageInfo<CmsContactWayVo>(pageNumber, pageSize);

		Pageable pageable = new QPageRequest(pageInfo.getPageNumber(), pageInfo.getPageSize(),
				QCmsContactWay.cmsContactWay.createTime.desc());
		Page page = cmsContactWayRepository.findAll(pageable);

		List<CmsContactWayVo> vos = new ArrayList<CmsContactWayVo>();
		page.getContent().forEach(baseInfo -> {
			vos.add((CmsContactWayVo) BeanUtil.copyProperties(new CmsContactWayVo(), baseInfo));
		});

		return pageInfo.execute(page, vos);
	}

}
